<template>
  <div class="login-container">
    <!--注册表单开-->
    <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="login-form" auto-complete="off"
             label-position="left" :class="isMobile?'mobile-container':'desktop-container'">
      <h3 class="title">新用户注册</h3>


      <el-form-item prop="nickname">
        <span class="svg-container">
          <svg-icon icon-class="user"/>
        </span>
        <el-input v-model="registerForm.nickname" name="nickname" type="text" placeholder="请输入用户名(2~25个字符)"/>
      </el-form-item>
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"/>
        </span>
        <el-input
          :type="pwdType"
          v-model="registerForm.password"
          name="password"
          placeholder="请输入密码(6~16个字符)"
          @keyup.enter.native="handleLogin"/>
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="pwdType === 'password' ? 'eye' : 'eye-open'"/>
        </span>
      </el-form-item>
      <el-form-item prop="phone">
        <span class="svg-container">
          <i class="el-icon-mobile-phone"></i>
        </span>
        <el-input v-model="registerForm.phone" name="phone" type="text" placeholder="请输入您的手机号"/>
      </el-form-item>
      <!--图片验证码开始-->
      <div v-show="showImageAuthInput" style="margin: -10px 1px 5px;">
        <el-row>
          <el-col :span="12">
            <img ref="imageCode" style="width: 165px; height: 45px;border-radius: 3px"
                 :src="authCodeImage">

          </el-col>
          <el-col :span="12" style="height: 48px; line-height: 40px;">
            <div style="float: right">
              <el-button size="small" type="text" @click="refreshImageCode">看不清？点此刷新</el-button>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-form-item v-show="showImageAuthInput" prop="imageAuthCode">
        <span class="svg-container">
          <i class="el-icon-warning"></i>
        </span>
        <el-input placeholder="请输入图片验证码"
                  v-model="registerForm.imageAuthCode" name="imageAuthCode" type="text">
        </el-input>
      </el-form-item>
      <!--图片验证码结束-->

      <!--短信验证码开始-->
      <el-row v-show="showTxtInput">
        <el-col :span="12">
          <el-form-item prop="authCode">
            <!--<span class="svg-container">
              <i class="el-icon-warning"></i>
            </span>-->
            <el-input placeholder="请输入短信验证码"
                      v-model="registerForm.authCode" name="authCode" type="text">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="height: 47px; line-height: 47px;">
          <div style="float: right">
            <el-button type="success" :disabled="sendTxtMsgDisabled" @click="sendTxtMsg">{{sendTxtMsgContent}}
            </el-button>
          </div>
        </el-col>
      </el-row>
      <!--短信验证码结束-->

      <!--底部操作栏-->
      <el-form-item>
        <el-button :loading="loading" :disabled="registerBtnDisabled" type="primary" style="width:100%;"
                   @click.native.prevent="handleRegister">
          注册
        </el-button>
      </el-form-item>
      <el-row style="margin-top: -10px">
        <el-col :span="12">
          <el-button type="text" @click="$router.push('/login')">登录账号</el-button>
        </el-col>
        <el-col :span="12">
          <div style="float: right">
            <el-button style="display: block" type="text" @click="$router.push('/reset_password')">忘记密码</el-button>
          </div>
        </el-col>
      </el-row>
      <!--底部操作栏-->
      <div style="text-align: center;color: white;margin-top: 20px">
        🔥小二科技有限公司@copy2019
      </div>
    </el-form>
    <!--注册表单结束-->

  </div>
</template>

<script>
  import {isMobile, isVaildMsgAuthCode, isValidImageCode, isValidPassword, isvalidUsername} from '@/utils/validate'
  import {verifyImageCode} from '@/api/login'
  import {registerUser, sendTextMessage, verifyTxtMsgCode} from '../../api/login'
  import {checkMobileAvailable} from '../../api/user-api'
  import {BASE_API} from "@/utils/request";

  export default {
    name: 'Register',
    data() {
      //验证短信验证码
      const validateTxtAuthCode = (rule, value, callback) => {
        if (!isVaildMsgAuthCode(value)) {
          callback(new Error('请输入六个数字的短信验证码'))
        } else {
          verifyTxtMsgCode(this.registerForm.phone, this.registerForm.authCode).then(res => {
            if (res) {
              callback()
            } else {
              callback(new Error('请输入正确的六个数字的短信验证码'))
            }
          })
          callback()
        }
      }
      //验证图片验证码
      const validateImageCode = (rule, value, callback) => {
        if (!isValidImageCode(value)) {
          callback(new Error('请输入正确的图片验证码'))
          this.showTxtInput = false
        } else {
          //调用远程接口判断验证码是否正确
          verifyImageCode(this.registerForm.phone, this.registerForm.imageAuthCode).then(res => {
            if (res) {
              this.showTxtInput = true
              this.sendTxtMsgDisabled = false
              callback()
            } else {
              callback(new Error('请输入正确的图片验证码'))
            }
          })
        }
      }
      //验证手机号
      const validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('请输入正确的手机号'))
          this.showImageAuthInput = false
          this.showTxtInput = false
        } else {
          checkMobileAvailable(value).then(res => {
            if (res) {
              this.authCodeImage = BASE_API + '/auth/verify_image.jpg?uid=' + value
              this.showImageAuthInput = true
              callback()
            } else {
              callback(new Error('该手机号已经注册,请直接登录'))
            }
          })
        }
      }
      //验证用户名
      const validateUsername = (rule, value, callback) => {
        if (!isvalidUsername(value)) {
          callback(new Error('请输入正确的用户名,用户名长度在2~25个字符之间'))
        } else {
          callback()
        }
      }
      //验证密码
      const validatePass = (rule, value, callback) => {
        if (!isValidPassword(value)) {
          callback(new Error('请输入正确的密码,密码由6-16个数字和字母组合'))
        } else {
          callback()
        }
      }
      return {
        registerBtnDisabled: false,//注册按钮是否可用，默认可用
        totalTime: 120, //发送验证码间隔时间
        authCodeImage: null, //图片验证码
        sendTxtMsgContent: '发送验证码', //发送短信验证码按钮文字
        sendTxtMsgDisabled: true,//发送短信按钮是否可用
        showTxtInput: false,//是否显示短信输入栏，默认不显示
        showImageAuthInput: false,//是否显示图片验证码输入，默认不显示
        isMobile: false, //是否在手机内注册
        //注册表单属性
        registerForm: {
          nickname: null,
          phone: null,
          password: null,
          imageAuthCode: null,
          authCode: null
        },
        //注册表单属性验证规则
        registerRules: {
          phone: [{required: true, trigger: 'change', validator: validateMobile}],
          nickname: [{required: true, trigger: 'blur', validator: validateUsername}],
          password: [{required: true, trigger: 'blur', validator: validatePass}],
          imageAuthCode: [{required: true, trigger: 'change', validator: validateImageCode}],
          authCode: [{required: true, trigger: 'change', validator: validateTxtAuthCode}]
        },
        loading: false,
        pwdType: '',
      }
    },
    methods: {
      //属性图片验证码
      refreshImageCode() {
        this.registerForm.imageAuthCode = null
        this.authCodeImage = null
        setTimeout(() => {
          this.authCodeImage = BASE_API + '/auth/verify_image.jpg?uid=' + this.registerForm.phone
        }, 1)
      },
      //发送验证码可用倒计时
      countDown() {
        if (this.sendTxtMsgDisabled) return  //改动的是这两行代码
        this.sendTxtMsgDisabled = true
        this.sendTxtMsgContent = this.totalTime + 's后重新发送'
        let clock = window.setInterval(() => {
          this.totalTime--
          this.sendTxtMsgContent = this.totalTime + 's后重新发送'
          if (this.totalTime < 0) {
            window.clearInterval(clock)
            this.sendTxtMsgContent = '重新发送'
            this.totalTime = 120
            this.sendTxtMsgDisabled = false  //这里重新开启
          }
        }, 1000)
      },
      //发送短信验证码
      sendTxtMsg() {
        //发送短信验证码
        sendTextMessage(this.registerForm.phone, this.registerForm.imageAuthCode).then(res => {
          if (res) {
            this.countDown()
          }
        })
      },
      //密码是否可见
      showPwd() {
        if (this.pwdType === 'password') {
          this.pwdType = ''
        } else {
          this.pwdType = 'password'
        }
      },
      //开始注册
      handleRegister() {
        this.$refs.registerForm.validate(valid => {
          if (valid) {
            //注册
            this.loading = true
            registerUser(this.registerForm).then(res => {
              this.loading = false
              this.$message.success("恭喜您注册成功！")
              this.$router.push({
                path: '/login',
                query: {
                  mobile: this.registerForm.phone
                }
              })
            }).catch(error => {
              this.loading = false
              console.log(error)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      checkViewPort() {
        const {body} = document
        const rect = body.getBoundingClientRect()
        this.isMobile = rect.width - 1 < 992
      }
    },
    mounted() {
      this.checkViewPort()
      console.log(BASE_API)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  $bg: #2d3a4b;
  $light_gray: #eee;

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 8px;
        color: $light_gray;
        height: 47px;

        &:-webkit-autofill {
          -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: #fff !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }

  .mobile-container {
    margin: 80px auto;
  }

  .desktop-container {
    margin: 180px auto;
  }


</style>

<style rel="stylesheet/scss" lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;
  .login-container {
    position: absolute;
    height: 100%;
    width: 100%;
    /*<!--background-color: $bg;-->*/
    background: url("../../assets/bg_chahua.jpg") no-repeat center;
    background-size: cover;
    overflow: hidden;

    .login-form {
      position: absolute;
      left: 0;
      right: 0;
      width: 450px;
      max-width: 95%;
      padding: 20px;
      background-color: #2d3a4b;
      opacity: 0.9;
      border-radius: 15px;

    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title {
      font-size: 26px;
      font-weight: 400;
      color: $light_gray;
      margin: 0px auto 20px auto;
      text-align: center;
      font-weight: bold;
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
  }
</style>

